package io.alvin.ch02;

/**
 * 错误的suspend方法使用
 * Created by Alvin on 2017/7/6.
 */
public class BadSuspendDemo {
    public static Object u = new Object();
    static ChangeObjectThread t1 = new ChangeObjectThread("t1");
    static ChangeObjectThread t2 = new ChangeObjectThread("t2");

    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            synchronized (u) {
                System.out.println("in " + getName());
                Thread.currentThread().suspend();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        t1.start();
        Thread.sleep(1000);
        t2.start();
        t1.resume();
        //Thread.sleep(1000); 注释后，t1.resume执行后t2启动，但是后面的t2.resume可能会在t2.suspend之前执行，导致t2被永久挂起。
        t2.resume();
        t1.join();
        t2.join();
    }
}
